//
//  ViewController.m
//  RefreshTestPod
//
//  Created by Clavis on 2018/12/21.
//  Copyright © 2018 Clavis. All rights reserved.
//

#import "ViewController.h"
#import <MJRefresh.h>

@interface ViewController () <UICollectionViewDataSource, UICollectionViewDelegate>
@property (nonatomic, strong) UICollectionView *collection;
@property (nonatomic, assign) NSInteger dataSource;
@end

@implementation ViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view, typically from a nib.
    
    self.collection = ({
        UICollectionViewFlowLayout *layout = [[UICollectionViewFlowLayout alloc] init];
        layout.itemSize = CGSizeMake(120, 80);
        layout.minimumLineSpacing = 10;
        layout.minimumInteritemSpacing = 10;
        UICollectionView *collection = [[UICollectionView alloc] initWithFrame:self.view.bounds collectionViewLayout:layout];
        collection.delegate = self;
        collection.dataSource = self;
        [collection registerClass:[UICollectionViewCell class] forCellWithReuseIdentifier:@"cell"];
        collection;
    });
    [self.view addSubview:self.collection];
    self.view.backgroundColor = [UIColor.grayColor colorWithAlphaComponent:0.5];
    self.collection.backgroundColor = [UIColor.grayColor colorWithAlphaComponent:0.5];
    
    
    self.view.backgroundColor = UIColor.whiteColor;
    self.collection.backgroundColor = UIColor.lightGrayColor;
 
    self.collection.mj_header = [MJRefreshNormalHeader headerWithRefreshingBlock:^{
        [self loadData:YES];
    }];

    self.collection.mj_footer = [MJRefreshBackStateFooter footerWithRefreshingBlock:^{
        NSLog(@"🎈 footer refresh");
        [self loadData:NO];
    }];
    
    
    self.collection.alwaysBounceVertical = YES;
    
    [self.collection.mj_header beginRefreshing];
}


- (void)loadData:(BOOL)isRefresh {
    dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(1 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
        
        [self.collection.mj_header endRefreshing];
        [self.collection.mj_footer endRefreshing];
        
        if (isRefresh) {
            self.dataSource = 3;
        } else {
            self.dataSource += 3;
        }
        
        [self.collection reloadData];
        
    });
}

- (NSInteger)numberOfSectionsInCollectionView:(UICollectionView *)collectionView {
    return 1;
}

- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section {
    return self.dataSource;
}

- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath {
    UICollectionViewCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:@"cell" forIndexPath:indexPath];
    cell.backgroundColor = [UIColor.orangeColor colorWithAlphaComponent:0.7];
    return cell;
}

@end
